import 'dart:async';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/create_smart_home_column_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_modify_order_list_item_widget.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

/// 智能家居调整顺序页
class SmartHomeColumnModifyOrderPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeColumnModifyOrderPage";

  final List<ColumnListBean> columnList;
  final String shid;

  const SmartHomeColumnModifyOrderPage(
      {Key key, this.columnList, this.shid})
      : super(key: key);

  @override
  _SmartHomeColumnModifyOrderPageState createState() =>
      _SmartHomeColumnModifyOrderPageState();

  ///跳转方法
  static Future<bool> navigatorPush(BuildContext context,
      List<ColumnListBean> columnList, String shid) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      SmartHomeColumnModifyOrderPage(
        columnList: columnList,
        shid: shid,
      ),
      routeName: SmartHomeColumnModifyOrderPage.ROUTER,
    );
  }
}

class _SmartHomeColumnModifyOrderPageState
    extends BaseState<SmartHomeColumnModifyOrderPage> {
  ValueNotifier<bool> _isAllowSaveValueNotifier;

  CommonListPageWidgetState<ColumnListBean, SmartHomeColumnResponseBean>
      mState;
  SmartHomeStoreDetailViewModel _viewModel;
  StreamSubscription _categoryUpdateStreamSubscription;
  String _cacheKey;

  //固定在前面，不调整位置的栏目id
  String _fixScid;
  @override
  void initState() {
    super.initState();
    _viewModel = new SmartHomeStoreDetailViewModel(this);
    _isAllowSaveValueNotifier = ValueNotifier(false);
    _categoryUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeCategoryEvent>()?.listen((event) {
      mState?.viewModel?.refresh();
    });
  }

  @override
  void dispose() {
    _isAllowSaveValueNotifier?.dispose();
    _categoryUpdateStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Color(0xFFF6F7F9),
        body: _toMainColumnWidget(),
      ),
    );
  }

  // Widget _toPlaceHolderWidget(){
  //   return ValueListenableBuilder(
  //       valueListenable: _viewModel?.statusTypeValueNotifier,
  //       builder:
  //           (BuildContext context, PlaceHolderStatusType value, Widget child) {
  //         return VgPlaceHolderStatusWidget(
  //           loadingStatus: value == PlaceHolderStatusType.loading,
  //           errorStatus: value == PlaceHolderStatusType.error,
  //           emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
  //           errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
  //           errorOnClick: () => _viewModel
  //               .getCategoryOnLine(widget?.shid, _cacheKey, null),
  //           loadingOnClick: () => _viewModel
  //               .getCategoryOnLine(widget?.shid, _cacheKey, null),
  //           child: child,
  //         );
  //       },
  //       child: _toMainColumnWidget());
  // }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg ?? "暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        _toAddCategoryWidget(),
        Expanded(child: _toListWidget()),
        // SingleChildScrollView(
        //   child: Column(
        //     children: [
        //
        //       _toBottomWidget()
        //     ],
        //   ),
        // ),
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "管理类别",
      isShowBack: true,
      backgroundColor: Colors.white,
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: ValueListenableBuilder(
        valueListenable: _isAllowSaveValueNotifier,
        builder: (BuildContext context, bool isAllowSave, Widget child) {
          return GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              if (!isAllowSave) {
                VgToastUtils.toast(context, "请调整要修改的顺序");
                return;
              }
              List<ColumnListBean> list = new List();
              list.addAll(mState?.data);
              if (list == null || list.isEmpty) {
                return;
              }
              if(StringUtils.isNotEmpty(_fixScid)){
                list.insert(0, new ColumnListBean(scid: _fixScid));
              }
              String scids = list.map((e) => e.scid).toList().join(",");
              List<int> orderList = new List();
              for (int i = 0; i < list.length; i++) {
                orderList.add(i);
              }
              String orders = orderList.join(",");
              _viewModel.modifyColumn(context, orders, scids);
            },
            child: CommonFixedHeightConfirmButtonWidget(
              isAlive: isAllowSave,
              width: 48,
              height: 24,
              unSelectBgColor: Color(0xffCFD4DB),
              selectedBgColor:
                  ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              unSelectTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              selectedTextStyle: TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                  fontWeight: FontWeight.w600),
              text: "保存",
            ),
          );
        },
      ),
    );
  }

  ///拖动可更改排序 新增栏目
  Widget _toAddCategoryWidget() {
    return Container(
      height: 35,
      padding: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Row(
        children: [
          Text(
            "长按拖动可更改顺序",
            style: TextStyle(fontSize: 12, color: Color(0xFF8B93A5)),
          ),
          Spacer(),
          Visibility(
            visible: false,
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                // CreateSmartHomeCategoryPage.navigatorPush(
                //     context, widget?.shid, "", 0, mState?.data?.length);
                CreateSmartHomeColumnPage.navigatorPush(
                    context, widget?.shid, "", 0, mState?.data?.length);
              },
              child: Container(
                height: 35,
                alignment: Alignment.center,
                child: Text(
                  "+新增栏目",
                  style: TextStyle(
                      fontSize: 12,
                      color:
                          ThemeRepository.getInstance().getPrimaryColor_1890FF()),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toListWidget() {
    return CommonListPageWidget<ColumnListBean,
        SmartHomeColumnResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "shid": widget?.shid ?? "",
      },
      parseDataFunc: (VgHttpResponse resp) {
        SmartHomeColumnResponseBean responseBean = SmartHomeColumnResponseBean.fromMap(resp?.data);
        if(responseBean != null && responseBean.data != null
            && responseBean.data.columnList != null && responseBean.data.columnList.length > 0){
          responseBean.data.columnList.removeAt(0);
          int index = -1;
          responseBean.data.columnList.forEach((element) {
            if("真实案例" == element?.name){
              index = responseBean.data.columnList.indexOf(element);
              _fixScid = element.scid;
            }
          });
          if(index != -1){
            responseBean.data.columnList.removeAt(index);
          }
        }
        return responseBean;
      },
      stateFunc: (CommonListPageWidgetState<ColumnListBean,
          SmartHomeColumnResponseBean>
          state) {
        mState = state;
      },
      itemBuilder: (BuildContext context, int index, itemBean) {
        return SmartHomeColumnModifyOrderListItemWidget(
          shid: widget?.shid,
          index: index,
          itemBean: itemBean,
          onAccept: (int start, int end) {
            _processState(start, end);
          },
        );
      },
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: Colors.white,
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFFEEEEEE),
          ),
        );

        // return divider;
      },
      netUrl: NetApi.SMART_HOME_GET_COLUMN_LIST,
      httpType: VgHttpType.get,
      customEmptyWidget: _defaultEmptyCustomWidget("暂无内容"),
      customErrorWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
      needBottomSaveWidget: true,
    );
  }

  _onTap(ColumnListBean itemBean) {}

  ///item
  Widget _toItemWidget(
      BuildContext context, ColumnListBean listBean, int index) {
    return _toDraggable(context, listBean, index);
  }

  Widget _toDraggable(
      BuildContext context, ColumnListBean listBean, int index) {
    final Widget child = _toContainerWidget(context, listBean, index);
    return LongPressDraggable<int>(
        data: index,
        maxSimultaneousDrags: 1,
        childWhenDragging: Opacity(
          opacity: 0.5,
          child: child,
        ),
        feedback: Material(
          child: Container(
            height: 60,
            decoration: BoxDecoration(boxShadow: [
              BoxShadow(color: Colors.white.withOpacity(0.5), blurRadius: 5)
            ]),
            width: ScreenUtils.screenW(context),
            child: _toContainerWidget(context, listBean, index),
          ),
        ),
        child: DragTarget<int>(
          onAccept: (int start) {
            _processState(start, index);
          },
          onWillAccept: (int fromIndex) {
            return true;
          },
          builder: (BuildContext context, candidateData,
              List<dynamic> rejectedData) {
            return child;
          },
        ));
  }

  Widget _toContainerWidget(
      BuildContext context, ColumnListBean listBean, int index) {
    String categoryName = listBean?.name;
    String stid = listBean?.scid;
    int count = listBean?.cnt;
    return Container(
      height: 50,
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Row(children: [
        Text(
          categoryName ?? "",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontSize: 14,
            color: ("00" == (listBean?.defaultflg ?? "00"))
                ? Color(0xFFB0B3BF)
                : ThemeRepository.getInstance().getCardBgColor_21263C(),
          ),
        ),
        Spacer(),
        Visibility(
          // visible: "00" != (listBean?.defaultflg ?? "00"),
          visible: false,
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              CreateSmartHomeColumnPage.navigatorPush(
                  context, widget?.shid, categoryName, count, index,
                  scid: stid);
            },
            child: Container(
              height: 50,
              width: 84,
              alignment: Alignment.center,
              child: Text(
                "编辑",
                style: TextStyle(fontSize: 12, color: Color(0xFF8B93A5)),
              ),
            ),
          ),
        ),
        Image.asset(
          "images/icon_edit_order.png",
          width: 20,
        ),
      ]),
    );
  }

  void _processState(int start, int end) {
    print("拖拽调整： $start - $end");
    List list = mState?.data;
    if (list == null || list.isEmpty) {
      return;
    }
    var removeItem = list.removeAt(start);
    list.insert(end, removeItem);
    mState?.setState(() {});
    _isAllowSaveValueNotifier?.value = true;
  }
}
